package tuling.netty.meix;

import cn.hutool.core.util.StrUtil;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @author RenGaoshuai
 * @date 2023/10/24 16:37
 * @description 非销售协议签署 签名工具类
 */
public class NonSalesSignUtils {


    /**
     * 公共参数封装
     * @param requestBody 入参
     * @return String
     */
    public static String packageParam(String appKey,String appseret, String requestBody){

        if(StrUtil.isEmpty(requestBody)){
            return null;
        }
        // 添加签名参数
        try {
            Map<String,String> textParams = new HashMap<>();
            // 添加协议级请求参数
            textParams.put("version", "1.0");
            textParams.put("appKey", appKey);
            textParams.put("format", "json");
            textParams.put("type", "sync");
            return signTopRequest(textParams, appseret, requestBody);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }



    /**
     * 排序签名
     * @param params 外部参数
     * @param secret 秘钥
     * @param body 请求体
     * @return String
     */
    public static String signTopRequest(Map<String, String> params, String secret, String body){
        try {
            // 第一步：检查参数是否已经排序
            ArrayList<String> keys = new ArrayList<>(params.keySet());
            Collections.sort(keys);
            // 第二步：把所有参数名和参数值串在一起
            StringBuilder query = new StringBuilder();
            query.append(secret);
            for (String key : keys)      {
                String value = params.get(key);
                if (!StrUtil.isEmpty(key) && !StrUtil.isEmpty(value))          {
                    query.append(key).append(value);
                }
            }
            // 验签包括request body，API version 2.1
            body.replaceAll("\n","");
            body.replaceAll("\t","");
            body.replaceAll("\r","");
            query.append(body);
            query.append(secret);
            // 第三步：使用MD5加密
            byte[] bytes;
            MessageDigest md5 = null;
            try{
                md5 = MessageDigest.getInstance("MD5");
            }catch (NoSuchAlgorithmException ignored){
                throw new Exception(ignored);
            }
            bytes = md5.digest(query.toString().getBytes("UTF-8"));
            // 第四步：把二进制转化为大写的十六进制
            StringBuilder sign = new StringBuilder();
            for (byte b : bytes) {
                String hex = Integer.toHexString(b & 0xFF);
                if (hex.length() == 1) {
                    sign.append("0");
                }
                sign.append(hex.toUpperCase());
            }
            return sign.toString();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取参数签名
     * @param appKey
     * @param secret
     * @param requestBody
     * @return
     */
    public static String getSign(String appKey,String secret, String requestBody){
        Map<String,String> textParams = new HashMap<>(8);
        // 添加协议级请求参数
        textParams.put("version", "1.0");
        textParams.put("appKey", appKey);
        textParams.put("format", "json");
        textParams.put("type", "sync");
        String signString =  signTopRequest(textParams, secret, requestBody);
        return signString;
    }

}

